const getCurrentDateTime = () => {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');

    return {
        year,
        month,
        day,
        hours,
        minutes,
        seconds,
        formatted: `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    };
}

/**
 * 检验日期时间字符串是否符合 YYYY-MM-DD HH:mm:ss 格式
 * @param {string} dateTimeStr - 日期时间字符串
 * @returns {boolean} 是否符合格式
 */
function isValidDateTimeFormat(dateTimeStr) {
    // 正则表达式匹配 YYYY-MM-DD HH:mm:ss 格式或者 YYYY-MM-DD 格式
    const dateTimeRegex = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
    const dateOnlyRegex = /^\d{4}-\d{2}-\d{2}$/;
    return dateTimeRegex.test(dateTimeStr) || dateOnlyRegex.test(dateTimeStr);
}


// 封装日志记录函数
const saveLog = async (mongoose, LOG_COLLECTION, {
    collection, params, user, IP, browser,
    system, resultCount, status, message
}) => {
    try {
        const currentDateTime = getCurrentDateTime();
        await mongoose.connection.db.collection(LOG_COLLECTION).insertOne({
            collection,
            params,
            user,
            IP,
            browser,
            system,
            time: currentDateTime.formatted,
            resultCount,
            status,
            message
        });
    } catch (err) {
        console.error("⚠️ Failed to save log:", err.message);
    }
}

const checkLogCollectionExists = async (mongoose, collections, LOG_COLLECTION) => {
    const logCollectionExists = collections.some(c => c.name === LOG_COLLECTION);
    if (!logCollectionExists) {
        console.log(`📝 Creating log collection: ${LOG_COLLECTION}`);
        await mongoose.connection.db.createCollection(LOG_COLLECTION);
        // 为日志集合创建索引以提高查询性能
        await mongoose.connection.db.collection(LOG_COLLECTION).createIndexes([
            { key: { time: -1 } },
            { key: { IP: 1 } },
            { key: { browser: 1 } },
            { key: { system: 1 } },
            { key: { params: 1 } },
            { key: { message: 1 } },
            { key: { user: 1 } },
            { key: { collection: 1 } },
            { key: { resultCount: 1 } },
            { key: { status: 1 } }
        ]);
        console.log(`✅ Log collection ${LOG_COLLECTION} created with indexes`);
    }

}

module.exports = {
    saveLog,
    checkLogCollectionExists,
    isValidDateTimeFormat
};